<?php
/**
 * 用户分群
 * Created by PhpStorm.
 * User: Liujianlin
 * Date: 2017/6/24
 * Time: 15:00
 */

namespace app\controllers\marketing;

use app\models\marketing\UserGroup;
use yii;
use app\components\Site;
use app\components\redis\RedisUserGroupTest;

class UserGroupRedisController extends \app\base\Controller
{
    public function init()
    {
        parent::init();
        $this->enableCsrfValidation = false;        // 禁用post的csrf验证
    }
    
    /**
     * 添加最近30登录用户
     */
    public function add30DayLoginUser($siteName)
    {
       
        $key = '30DayLoginUser';
        $curTime = time();
        $appropriateTime = $curTime-30*24*3600;
        $sql = "select user_id from user_{$siteName} where last_login >  {$appropriateTime}";
        
        // 查询相关数据
        $userIdArr =  yii::$app->db->createCommand($sql)->queryAll();
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sadd($key,$userIdArr);
        return $redisUserGroupTest->smembers($key);
        
    }
    
    /**
     * 30注册用户加入购物车时间
     */
    public function add30DayRegisterUser($siteName)
    {
       
        $key = '30DayRegisterUser';
        $curTime = time();
        $appropriateTime = $curTime-30*24*3600;
        $sql = "select user_id from user_{$siteName} where reg_date >  {$appropriateTime}";
        
        // 查询相关数据
        $userIdArr =  yii::$app->db->createCommand($sql)->queryAll();
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sadd($key,$userIdArr);
        return $redisUserGroupTest->smembers($key);
        
    }
    
    /**
     * 英语用户
     */
    public function addEnUser($siteName)
    {
        $key = 'EnUser';
        $curTime = time();
        $start = 0;
        $sqlCount = "select count(user_id) from user_{$siteName} where lang = 'en' ";
        $userCount = yii::$app->db->createCommand($sqlCount)->queryScalar();
        $redisUserGroupTest = new RedisUserGroupTest();
        for ($start = 0 ; $start < $userCount; $start = $start + 100000  ) {
            $sql = "select user_id from user_{$siteName} where lang = 'en' limit {$start},100000 ";
             // 查询相关数据
            $userIdArr =  yii::$app->db->createCommand($sql)->queryAll();
            
            $redisUserGroupTest->sadd($key,$userIdArr);
        }
        
        
       
        return $redisUserGroupTest->smembers($key);
        
    }
    
    /**
     * 法语用户
     */
    public function addFrUser($siteName)
    {
        $key = 'FrUser';
        $curTime = time();
        
        $sql = "select user_id from user_{$siteName} where lang = 'fr'";
        
        // 查询相关数据
        $userIdArr =  yii::$app->db->createCommand($sql)->queryAll();
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sadd($key,$userIdArr);
        return $redisUserGroupTest->smembers($key);
        
    }
    
    /**
     * 退订用户
     */
    public function addTdUser($siteName)
    {
       
        $key = 'TdUser';
        $curTime = time();
        
        $sql = "select user_id from user_{$siteName} where is_received_promo = 0";
        
        // 查询相关数据
        $userIdArr =  yii::$app->db->createCommand($sql)->queryAll();
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sadd($key,$userIdArr);
        return $redisUserGroupTest->smembers($key);
        
    }
    
    /**
     * 弹出用户
     */
    public function addTcUser($siteName)
    {
        $key = 'TcUser';
        $curTime = time();
        
        $sql = "select user_id from user_{$siteName} where is_bound = 1";
        
        // 查询相关数据
        $userIdArr =  yii::$app->db->createCommand($sql)->queryAll();
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sadd($key,$userIdArr);
        return $redisUserGroupTest->smembers($key);
        
    }
    /**
     * 把数据添加到redis
     */
    public function actionAddGroupToRedis()
    {
        set_time_limit(0);
       
        ini_set('memory_limit', '1024M');
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        
        $siteId = $formData['site_id'];
        $siteName = Yii::$app->params['sites']['marketing_email']['web_index'][$siteId];
        if (isset($formData['buzhou']) && $formData['buzhou'] == 1) {
            echo "添加最近30天登录用户加入redis开始时间：" . date('Y-m-d H:i:s',time()).'<br>';
            $members = $this->add30DayLoginUser($siteName);
            $nums = count($members);
            echo "添加最近30天登录用户加入redis结束时间：" . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
        }
        
         ob_flush();
         flush();
        if (isset($formData['buzhou']) && $formData['buzhou'] == 2) {
            echo "添加最近30天注册用户加入redis开始时间：" . date('Y-m-d H:i:s',time()).'<br>';
            $members = $this->add30DayRegisterUser($siteName);
             $nums = count($members);
            echo "添加最近30天注册用户加入redis结束时间：" . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
         
        }
        ob_flush();
         flush();
        if (isset($formData['buzhou']) && $formData['buzhou'] == 3) {
            echo "英语用户加入redis开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
            $members = $this->addEnUser($siteName);
             $nums = count($members);
            echo "英语用户加入redis结束时间：" . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
        }
         ob_flush();
         flush();
        if (isset($formData['buzhou']) && $formData['buzhou'] == 4) {
            echo "法语用户加入redis开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
            $members = $this->addFrUser($siteName);
             $nums = count($members);
            echo "法语用户加入redis结束时间：" . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
        }
         ob_flush();
         flush();
        if (isset($formData['buzhou']) && $formData['buzhou'] == 5) {
            echo "退订用户加入redis开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
            $members = $this->addTdUser($siteName);
             $nums = count($members);
            echo "退订用户加入redis结束时间：" . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
        }
         ob_flush();
         flush();
        if (isset($formData['buzhou']) && $formData['buzhou'] == 6) {
            echo "弹出用户加入redis开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
            $members = $this->addTcUser($siteName);
             $nums = count($members);
            echo "弹出用户加入redis结束时间：" . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
        }
         ob_flush();
         flush();
        if (isset($formData['buzhou']) && $formData['buzhou'] == 7) {
        // 计算注册和登录用户的并集生成集合rgA
        echo "计算注册和登录用户的并集生成集合rgA开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
        $key1 = 'rgA';
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sunionstore($key1,'30DayLoginUser','30DayRegisterUser');
        $members = $redisUserGroupTest->smembers($key1);
         $nums = count($members);
        echo "计算注册和登录用户的并集生成集合rgA结束时间: " . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
         ob_flush();
         flush();
        
        // 计算英语法语用户的并集生成集合B
        echo "计算英语法语用户的并集生成集合efB开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
        $key2 = 'efB';
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sunionstore($key2,'EnUser','FrUser');
        $members = $redisUserGroupTest->smembers($key2);
         $nums = count($members);
        echo "计算注册和登录用户的并集生成集合efB结束时间: " . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
         ob_flush();
         flush();
        // 计算退订弹出用户的并集生成集合C
        echo "计算退订弹出用户的并集生成集合ttC开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
        $key3 = 'ttC';
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sunionstore($key3,'TdUser','TcUser');
        $members = $redisUserGroupTest->smembers($key3);
         $nums = count($members);
        echo "计算退订弹出用户的并集生成集合efB结束时间: " . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
         ob_flush();
         flush();
        $key4 = 'jihe4';
        echo "计算{$key1}集合和{$key2}的交集生成集合{$key4}开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
      
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sinterstore($key4,$key1,$key2);
        $members = $redisUserGroupTest->smembers($key4);
         $nums = count($members);
        echo "计算{$key1}集合和{$key2}的交集生成集合{$key4}结束时间: " . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
         ob_flush();
         flush();
        $key5 = 'jihe5';
        echo "计算{$key4}集合和{$key3}的差集生成集合{$key5}开始时间: " . date('Y-m-d H:i:s',time()).'<br>';
       
        $redisUserGroupTest = new RedisUserGroupTest();
        $redisUserGroupTest->sdiffstore($key5,$key4,$key3);
        $members = $redisUserGroupTest->smembers($key5);
         $nums = count($members);
        echo "计算{$key4}集合和{$key3}的差集生成集合{$key5}结束时间: " . date('Y-m-d H:i:s',time())."，共{$nums}条数据<br>";
        }
        
        
        // 
        // echo '111111<br>';
        // ob_flush();
        // flush();
        // sleep(10);
        // echo '222222<br>';
        // ob_flush();
        // flush();
        // sleep(10);
        // echo '33333<br>';
         // ob_flush();
        // flush();
        // 最近30天
    }
    
    /**
     * 分群列表
     * @return string
     */
    public function actionIndex()
    {
        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id");
        $reviserRealName = yii::$app->request->$method("reviser_real_name");

        $userGroupModel = new UserGroup();
        $condition['is_del'] = 0;
        $condition['user_group_type'] = 1;
        if (empty($siteId)) {
            if (empty($accessSiteInfo)) {
                $this->sysMsg('警告', '你的账号没有权限!',
                    [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            $curSite = current($accessSiteInfo);
            $siteId = $curSite['site_id'];
        }
        $condition['site_id'] = $siteId;

        $this->checkSitePrivilege($siteId);    // 校验用户是否具有站点的权限

        if (empty($reviserRealName)) {
            $session    = Yii::$app->session;
            $reviserRealName = $session['admin_info']['real_name'];
        }
        if ($reviserRealName != "全部") {
            $condition['reviser_real_name'] = $reviserRealName;
        }
        $groupList = $userGroupModel->getByCondition($condition, "order by user_group_id desc");
        foreach($groupList as $key => $group) {
            $formData = json_decode($group['form_data'], true);
            $groupList[$key]['item'] = $this->getPreviewItem($formData);
        }
        $reviser = $userGroupModel->getReviser();
        array_unshift($reviser, ["reviser_real_name" => "全部"]);
        $sysGroup = $userGroupModel->getSysGroup($siteId);

        return $this->render("//marketing/user-group/list",
            ["siteInfo" => $accessSiteInfo, "groupList" => $groupList,
                'sysGroup' => $sysGroup, "reviser" => $reviser,
                "requestData" => ["site_id" => $siteId, "reviser_real_name" => $reviserRealName]
            ]);
    }

    /**
     * 添加分群
     * @return string
     */
    public function actionAdd()
    {
        yii::$app->params['now_addr'] = "用户分群";

        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        return $this->render("//marketing/user-group/add", ["data" => $accessSiteInfo]);
    }

    /**
     * 分群添加确认
     */
    public function actionDoAdd()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();

        $verify = $this->verifyAddData($formData);
        if (true !== $verify) {
            $this->returnJson($verify[0], $verify[1]);
        }

        $this->checkSitePrivilege($formData['site_id']);    // 校验用户是否具有站点的权限
        $data = $this->getAddData($formData);
        $session    = Yii::$app->session;
        $data['reviser_real_name'] = $session['admin_info']['real_name'];
        $data['user_group_type'] = 1;
        $data['is_sys'] = 0;

        // 获取用户数
        $regCon = json_decode($data['reg_con'], true);
        $loginCon = json_decode($data['login_con'], true);
        $orderCon = json_decode($data['order_con'], true);
        $mailCon = json_decode($data['mail_con'], true);
        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        $summaryCount = $userGroupModel->getCount($siteName, 0, $regCon, $loginCon, $orderCon, $mailCon);
        $data['user_count'] = $summaryCount;
        $data['update_time'] = time();
        $data['use_time'] = time();

        // 添加到数据库
        $userGroupModel = new UserGroup();
        $userGroupModel->addUserGroup($data);
        $this->returnJson(0, "success");
    }

    /**
     * 验证添加分群数据
     * @param $formData
     * @return bool|string
     */
    private function verifyAddData($formData)
    {
        if (empty($formData['site_id'])) {
            return [10008, "请选择站点"];
        }
        if (empty($formData['user_group_name'])) {
            return [10009, "请填写分群名称"];
        }
        if (!isset($formData['user_group_id'])) {
            return [10010, "不存在分群id"];
        }
        if (!isset($formData['register_state'], $formData['login_state'])
            || !isset($formData['order_state'], $formData['mail_state'])
        ) {
            return [10011, "数据不完整"];
        }
        if (empty($formData['register_state']) && empty($formData['login_state'])
            && empty($formData['order_state']) && empty($formData['mail_state'])
        ) {
            return [10011, "数据不完整"];
        }

        $isDup = $this->isDuplicate($formData['site_id'], $formData['user_group_name'], $formData['user_group_id']);
        if ($isDup) {
            return [10012, "分群名称重复"];
        }

        return true;
    }

    /**
     * 获取添加分群的数据
     * @param $formData
     * @return mixed
     */
    private function getAddData($formData)
    {
        $data['site_id'] = $formData['site_id'];
        $data['user_group_name'] = $formData['user_group_name'];
        $data['description'] = $formData['description'];
        $data['form_data'] = json_encode($formData);

        $freqArr = [
            "1" => ["equal_frequency" => 1],
            "2" => ["min_frequency" => 2, "max_frequency" => 4],
            "3" => ["min_frequency" => 5, "max_frequency" => 7],
            "4" => ["min_frequency" => 8, "max_frequency" => 9],
            "5" => ["min_frequency" => 10]
        ];

        // 注册相关条件
        $regCon['state'] = $formData['register_state'];
        if (1 == $formData['register_time_type']) {     // 指定近几天
            if (!empty($formData['register_near_days'])) {
                $regCon['near_days'] = $formData['register_near_days'];
            }
        } else {                                // 指定时间区间
            if (!empty($formData['register_start_time'])) {
                $regCon['start_time'] = yii::$app->bjTime->strtotime($formData['register_start_time']);
            }
            if (!empty($formData['register_end_time'])) {
                $regCon['end_time'] = yii::$app->bjTime->strtotime($formData['register_end_time']);
            }
        }

        // 登录相关条件
        $loginCon['state'] = $formData['login_state'];
        if (1 == $formData['login_time_type']) {        // 指定近几天
            if (!empty($formData['login_near_days'])) {
                $loginCon['near_days'] = $formData['login_near_days'];
            }
        } else {            // 指定时间区间
            if (!empty($formData['login_start_time'])) {
                $loginCon['start_time'] = yii::$app->bjTime->strtotime($formData['login_start_time']);
            }
            if (!empty($formData['login_end_time'])) {
                $loginCon['end_time'] = yii::$app->bjTime->strtotime($formData['login_end_time']);
            }
        }
        // 登录频次条件
        if (isset($formData['login_frequency']) && key_exists($formData['login_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['login_frequency']] as $freqKey => $freqValue) {
                $loginCon[$freqKey] = $freqValue;
            }
        }

        // 下单相关条件
        $orderCon['state'] = $formData['order_state'];
        if (1 == $formData['order_time_type']) {    // 指定近几天
            if (!empty($formData['order_near_days'])) {
                $orderCon['near_days'] = $formData['order_near_days'];
            }
        } else {                // 指定时间区间
            if (!empty($formData['order_start_time'])) {
                $orderCon['start_time'] = yii::$app->bjTime->strtotime($formData['order_start_time']);
            }
            if (!empty($formData['order_end_time'])) {
                $orderCon['end_time'] = yii::$app->bjTime->strtotime($formData['order_end_time']);
            }
        }
        // 下单频次条件
        if (isset($formData['order_frequency']) && key_exists($formData['order_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['order_frequency']] as $freqKey => $freqValue) {
                $orderCon[$freqKey] = $freqValue;
            }
        }

        // 邮件行为
        $mailCon['state'] = $formData['mail_state'];
        if (1 == $formData['mail_time_type']) {     // 指定近几天
            if (!empty($formData['mail_near_days'])) {
                $mailCon['near_days'] = $formData['mail_near_days'];
            }
        } else {        // 指定时间区间
            if (!empty($formData['mail_start_time'])) {
                $mailCon['start_time'] = yii::$app->bjTime->strtotime($formData['mail_start_time']);
            }
            if (!empty($formData['mail_end_time'])) {
                $mailCon['end_time'] = yii::$app->bjTime->strtotime($formData['mail_end_time']);
            }
        }
        // 邮件打开频次
        if (isset($formData['mail_open_frequency']) && key_exists($formData['mail_open_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['mail_open_frequency']] as $freqKey => $freqValue) {
                if ($freqKey == "min_frequency") {
                    $freqKey = "min_open_frequency";
                } else if ($freqKey == "equal_frequency") {
                    $freqKey = "equal_open_frequency";
                } else if ($freqKey == "max_frequency") {
                    $freqKey = "max_open_frequency";
                } else {
                    // do nothing
                }
                $mailCon[$freqKey] = $freqValue;
            }
        }
        // 邮件点击频次
        if (isset($formData['mail_click_frequency']) && key_exists($formData['mail_click_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['mail_click_frequency']] as $freqKey => $freqValue) {
                if ($freqKey == "min_frequency") {
                    $freqKey = "min_click_frequency";
                } else if ($freqKey == "equal_frequency") {
                    $freqKey = "equal_click_frequency";
                } else if ($freqKey == "max_frequency") {
                    $freqKey = "max_click_frequency";
                } else {
                    // do nothing
                }
                $mailCon[$freqKey] = $freqValue;
            }
        }

        $data['reg_con'] = json_encode($regCon);
        $data['login_con'] = json_encode($loginCon);
        $data['order_con'] = json_encode($orderCon);
        $data['mail_con'] = json_encode($mailCon);
        return $data;
    }

    /**
     * 编辑分群
     * @return string
     */
    public function actionEdit()
    {
        yii::$app->params['now_addr'] = "用户分群";
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method("user_group_id");
        if (empty($userGroupId)) {
            $this->sysMsg('警告', "参数不完整",
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }

        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        $userGroupModel = new UserGroup();
        $group = $userGroupModel->getByCondition(['user_group_id' => $userGroupId]);
        if (empty($group)) {
            $this->sysMsg('警告', "不存在该分群",
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $formData = json_decode($group[0]['form_data'], true);
        $data = $formData;
        $data['user_group_id'] = $group[0]['user_group_id'];
        return $this->render("//marketing/user-group/edit",
            ["data" => $data, "siteInfo" => $accessSiteInfo]);
    }

    /**
     * 编辑分群确认
     */
    public function actionDoEdit()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();

        $verify = $this->verifyAddData($formData);
        if (true !== $verify) {
            $this->returnJson($verify[0], $verify[1]);
        }

        $this->checkSitePrivilege($formData['site_id']);    // 校验用户是否具有站点的权限
        $data = $this->getAddData($formData);
        $session    = Yii::$app->session;
        $data['reviser_real_name'] = $session['admin_info']['real_name'];
        $data['user_group_type'] = 1;
        $data['is_sys'] = 0;

        // 获取用户数
        $regCon = json_decode($data['reg_con'], true);
        $loginCon = json_decode($data['login_con'], true);
        $orderCon = json_decode($data['order_con'], true);
        $mailCon = json_decode($data['mail_con'], true);
        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        $summaryCount = $userGroupModel->getCount($siteName, 0, $regCon, $loginCon, $orderCon, $mailCon);
        $data['user_count'] = $summaryCount;
        $data['update_time'] = time();
        $data['use_time'] = time();

        // 添加到数据库
        $userGroupModel = new UserGroup();
        $userGroupModel->updateByCondition(['user_group_id' => $formData['user_group_id']],
            ["is_del" => 1, "reviser_real_name" => $data['reviser_real_name'], "del_time" => time()]);
        $userGroupModel->addUserGroup($data);
        
        //$userGroupModel->updateByCondition(['user_group_id' => $formData['user_group_id']], $data);
        $this->returnJson(0, "success");
    }

    /**
     * 删除分群
     */
    public function actionDel()
    {
        yii::$app->params['now_addr'] = "用户分群";
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method('user_group_id');
        $userGroupModel = new UserGroup();
        $session    = Yii::$app->session;
        $data['del_real_name'] = $session['admin_info']['real_name'];
        $data['del_time'] = time();
        $data['is_del'] = 1;
        try {
            $userGroupModel->updateByCondition(["user_group_id" => $userGroupId], $data);
        } catch(\Exception $e) {
            $this->returnJson(10008, "系统繁忙，请重试", "");
        }

        $this->returnJson(0, "success", "");
    }

    public function actionListData()
    {
        return $this->render("//marketing/user-group/list-data", ["data" => ""]);
    }

    /**
     * 添加队列
     * @return string
     */
    public function actionAddSendQueue()
    {
        set_time_limit(0);
        yii::$app->params['now_addr'] = "用户分群";
        $data = $this->getAddSendQueueData();
        if (is_string($data)) {
            echo $data;
            exit();
        }

        $data['channel'] = [2 => 'emarsys', 4 => 'cheet', 6 => 'emarsys_new'];

        return $this->render('/marketing/user-group/add-send-queue', [
            'data' => $data
        ]);
    }

    /**
     * 获取 添加发送队列 的数据
     * @return string
     */
    private function getAddSendQueueData()
    {
        $method = yii::$app->request->getMethod();
        $data = yii::$app->request->$method();

        if (!isset($data['site_id'])) {
            return "数据不完整";
        }

        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        if (empty($siteName)) {
            return "站点不存在";
        }
        $data['brief_code'] = Site::getInstance()->getBriefCode($data['site_id']);
        if (empty($data['brief_code'])) {
            return "站点没有简码";
        }

        $data['site_name'] = $siteName;

        $data['user_define_group'] = yii::$app->request->$method("user_define_group", []);    // 自定义分群
        $data['sys_group'] = yii::$app->request->$method("sys_group", []);               // 系统分群
        $data['exclude_group'] = yii::$app->request->$method("exclude_group", []);       // 排除分群

        // 获取用户
        $userGroupModel = new UserGroup();
        $data['user_count'] = $userGroupModel->getMergeGroupCount($siteName, $data['user_define_group'],
                                $data['sys_group'], $data['exclude_group']);

        $template = new \app\models\marketing\MailTemplate();
        $data['template'] = $template->getTemplateDetailBySite($data['site_id']);
        foreach ($data["template"] as $key => $value) {
            $data['template'][$key]['group_name_prefix'] = $value['template_type_compaign'];
            if (empty($value['template_type_compaign'])) {     // 如果compaign为空，则使用模板名来作为分组名的前缀
                $data['template'][$key]['group_name_prefix'] = $value['template_name'];
            }
        }

        $data['mail'] = Site::getInstance()->getMailSender($data['site_id']);

        return $data;
    }

    /**
     * 分群预览
     */
    public function actionPreviewAjax()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $verify = $this->verifyAddData($formData);
        if (true !== $verify && 10012 !=  $verify[0]) {
            $this->returnJson($verify[0], $verify[1]);
        }

        $this->checkSitePrivilegeAjax($formData['site_id']);    // 校验用户是否具有站点的权限
        $returnData = $this->doPreview($formData);

        $this->returnJson(0, "success", $returnData);
    }

    /**
     * 实际分群预览操作
     * @param $formData
     * @return mixed
     */
    private function doPreview($formData)
    {
        $data = $this->getAddData($formData);
       
        $data['reg_con'] = json_decode($data['reg_con'], true);
        $data['login_con'] = json_decode($data['login_con'], true);
        $data['order_con'] = json_decode($data['order_con'], true);
        $data['mail_con'] = json_decode($data['mail_con'], true);


        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        $summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
                                $data['login_con'], $data['order_con'], $data['mail_con']);
        $summary = ["name" => "已选分群用户（合并去重）", "count" => $summaryCount];

        $item = $this->getPreviewItem($formData);

        $returnData['summary'] = $summary;
        $returnData['item'] = $item;
        return $returnData;
    }

    /**
     * 获取预览中的选项
     * @param $formData
     * @return array
     */
    public function getPreviewItem($formData)
    {
        $item = [];

        $freqNameArr = [
            "1" => "1次",
            "2" => "2~4次",
            "3" => "5~7次",
            "4" => "8~9次",
            "5" => "10次以上"
        ];

        // 注册
        if (0 != $formData['register_state']) {
            $regName = "";
            if (1 == $formData['register_time_type']) {        // 指定近几天
                if (!empty(is_numeric($formData['register_near_days']))) {
                    $regName .= "近{$formData['register_near_days']}天 ";
                }
            } else {
                if (!empty($formData['register_start_time'])) {
                    $regName .= "{$formData['register_start_time']}";
                }
                if (!empty($formData['register_end_time'])) {
                    $regName .= "~{$formData['register_end_time']} ";
                }
            }
            if (1 == $formData['register_state']) {
                $regName .= "未注册";
            } else {
                $regName .= "注册";
            }
            //$regCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'], [], [], []);
            $item[] = ["name" => $regName, "count" => ""];
        }

        // 登录
        if (0 != $formData['login_state']) {
            $name = "";
            if (1 == $formData['login_time_type']) {        // 指定近几天
                if (!empty(is_numeric($formData['login_near_days']))) {
                    $name .= "近{$formData['login_near_days']}天 ";
                }
            } else {
                if (!empty($formData['login_start_time'])) {
                    $name .= "{$formData['login_start_time']}";
                }
                if (!empty($formData['login_end_time'])) {
                    $name .= "~{$formData['login_end_time']} ";
                }
            }
            if (1 == $formData['login_state']) {
                $name .= "从未登录";
            } else {
                $name .= "登录";
            }
            if (!empty($formData['login_frequency']) && key_exists($formData['login_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['login_frequency']]} ";
            }
            //$loginCount = $userGroupModel->getCount($siteName, 0, [], $data['login_con'], [], []);
            $item[] = ["name" => $name, "count" => ""];
        }

        // 下单
        if (0 != $formData['order_state']) {
            $name = "";
            if (1 == $formData['order_time_type']) {    // 指定近几天
                if (!empty(is_numeric($formData['order_near_days']))) {
                    $name .= "近{$formData['order_near_days']}天 ";
                }
            } else {
                if (!empty($formData['order_start_time'])) {
                    $name .= "{$formData['order_start_time']}";
                }
                if (!empty($formData['order_end_time'])) {
                    $name .= "~{$formData['order_end_time']} ";
                }
            }

            if (1 == $formData['order_state']) {
                $name .= "从未下单";
            } else {
                $name .= "下单";
            }

            if (!empty($formData['order_frequency']) && key_exists($formData['order_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['order_frequency']]} ";
            }
            //$orderCount = $userGroupModel->getCount($siteName, 0, [], [], $data['order_con'], []);
            $item[] = ["name" => $name, "count" => ""];
        }


        if (0 != $formData['mail_state']){
            $name = "";
            if (1 == $formData['mail_time_type']) {
                if (!empty(is_numeric($formData['mail_near_days']))) {
                    $name .= "近{$formData['mail_near_days']}天 ";
                }
            } else {
                if (!empty($formData['mail_start_time'])) {
                    $name .= "{$formData['mail_start_time']}";
                }
                if (!empty($formData['mail_end_time'])) {
                    $name .= "~{$formData['mail_end_time']} ";
                }
            }
            $mailStateArr = [1 => "从未发送", 3 => "已发送", 2 => "发送未打开", 4 => "邮件打开", 5 => "打开未点击", 6 => "打开并点击"];
            if (key_exists($formData['mail_state'], $mailStateArr)) {
                $name .= " " . $mailStateArr[$formData['mail_state']];
            }
            if (!empty($formData['mail_open_frequency']) && key_exists($formData['mail_open_frequency'], $freqNameArr)) {
                $name .= " 且打开次数{$freqNameArr[$formData['mail_open_frequency']]} ";
            }
            if (!empty($formData['mail_click_frequency']) && key_exists($formData['mail_click_frequency'], $freqNameArr)) {
                $name .= " 且点击次数{$freqNameArr[$formData['mail_click_frequency']]} ";
            }
            //$mailCount = $userGroupModel->getCount($siteName, 0, [], [], [], $data['mail_con']);
            $item[] = ["name" => $name, "count" => ""];

        }
        return $item;
    }

    /**
     * 刷新用户数
     */
    public function actionFlashUserCount()
    {
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method('user_group_id');
        if (empty($userGroupId)) {
            $this->returnJson(10008, "数据不完整，没有提交分群id");
        }

        $userGroupModel = new UserGroup();
        $condition = ["user_group_id" => $userGroupId];
        $group = $userGroupModel->getByCondition($condition);
        if (empty($group)) {
            $this->returnJson(10009, "分群不存在");
        }

        $formData = json_decode($group[0]['form_data'], true);
        $this->checkSitePrivilegeAjax($group[0]['site_id']);    // 校验用户是否具有站点的权限

        $summaryCount = $this->doFlashUserDefineCount($userGroupId, $formData);
        $flashTime = yii::$app->bjTime->date("Y-m-d H:i");
        $this->returnJson(0, "success", ["count" => $summaryCount, 'flash_time' => $flashTime]);
    }

    /**
     * 刷新自定义分群的用户数
     * @param $userGroupId
     * @param $formData
     * @return mixed
     */
    private function doFlashUserDefineCount($userGroupId, $formData)
    {
        $userGroupModel = new UserGroup();
        $data = $this->getAddData($formData);
        $data['reg_con'] = json_decode($data['reg_con'], true);
        $data['login_con'] = json_decode($data['login_con'], true);
        $data['order_con'] = json_decode($data['order_con'], true);
        $data['mail_con'] = json_decode($data['mail_con'], true);

        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        $summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
            $data['login_con'], $data['order_con'], $data['mail_con']);
        $userGroupModel->updateByCondition(["user_group_id" => $userGroupId],
            ["user_count" => $summaryCount, "update_time" => time()]);
        return $summaryCount;
    }

    /**
     * 刷新系统分群的用户数
     * @param $userGroupId
     * @param $siteId
     * @param $otherCon
     */
    private function doFlashSysCount($userGroupId, $userGroupType, $siteId, $otherCon)
    {
        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($siteId);
        $summaryCount = $userGroupModel->getSysCount($userGroupId, $userGroupType, $siteName, $otherCon);
        $userGroupModel->updateByCondition(["user_group_id" => $userGroupId],
            ["user_count" => $summaryCount, "update_time" => time()]);
    }

    /**
     * 定时刷新任务
     */
    public function actionFlashCountCron()
    {
        // 忽略用户中断，并且无限时执行
        ignore_user_abort(true);
        set_time_limit(0);

        $userGroupModel = new UserGroup();
        $groupList = $userGroupModel->getByCondition(['is_del' => 0]);
        $curTime = time();
        $maxIntervalTime = 30 * 86400;  // 最大使用的间隔时间:30天
        foreach ($groupList as $group) {
            if (1 == $group['user_group_type']) {   // 自定义分群
                if ($group['use_time'] - $curTime > $maxIntervalTime) {     // 超过最大间隔时间不用更新
                    continue;
                }
                $formData = json_decode($group['form_data'], true);
                try {
                    $this->doFlashUserDefineCount($group['user_group_id'], $formData);
                } catch (\Exception $e) {
                    echo "刷新user_group_id[{$group['user_group_id']}]失败： " . $e->getMessage() . "<br/>";
                    continue;
                }
            } else {            // 系统分群
                $otherCon = json_decode($group['other_con'], true);
                $this->doFlashSysCount($group['user_group_id'], $group['user_group_type'], $group['site_id'], $otherCon);
            }
        }
        echo "刷新完成";
    }

    /**
     * 获取合并分群的用户数
     */
    public function actionMergeGroupCount()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id", 0);
        $userDefineGroup = yii::$app->request->$method("user_define_group", []);    // 自定义分群
        $sysGroup = yii::$app->request->$method("sys_group", []);               // 系统分群
        $excludeGroup = yii::$app->request->$method("exclude_group", []);       // 排除分群

        $siteName = Site::getInstance()->getSiteShortNameById($siteId);
        if (empty($siteName)) {
            $this->returnJson(10008, "站点不存在", []);
        }

        if (empty($userDefineGroup) && empty($sysGroup)) {      // 没有给自定义分群、系统分群条件的，直接返回0
            $this->returnJson(0, "success", ["count" => 0]);
        }

        $userGroupModel = new UserGroup();
        $count = $userGroupModel->getMergeGroupCount($siteName, $userDefineGroup, $sysGroup, $excludeGroup);
        $this->returnJson(0, "success", ["count" => $count]);
    }

    /**
     * 是否有重复的分群
     */
    public function actionIsDuplicate()
    {
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method("user_group_id");
        $siteId = yii::$app->request->$method("site_id");
        $groupName = yii::$app->request->$method("user_group_name");
        var_dump($groupName);

        if (empty($siteId) || empty($groupName)) {
            $this->returnJson(10001, "数据不完整");
        }

        $result = $this->isDuplicate($siteId, $groupName, $userGroupId);
        if (false === $result) {
            $this->returnJson(0, "success", ["is_duplicate" => 0]);
        } else {
            $this->returnJson(0, "success", ["is_duplicate" => 1]);
        }
    }

    /**
     * 是否有重复的分群
     * @param $siteId                   站点id
     * @param $userGroupName            分群名称
     * @param null $userGroupId         分群id
     * @return bool
     */
    private function isDuplicate($siteId, $userGroupName, $userGroupId = null)
    {
        $userGroupModel = new UserGroup();
        $group = $userGroupModel->getByCondition(["site_id" => $siteId, "user_group_name" => $userGroupName, "is_del" => 0]);
        if (empty($group)) {
            return false;
        }
        if (!empty($userGroupId) && $userGroupId == $group[0]["user_group_id"]) {
            return false;
        }
        return true;
    }
}
